package com.ns.dcjh.utils;

import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;

import com.ns.dcjh.R;

import java.lang.ref.WeakReference;

public class LoadingUtils {
    private WeakReference<Context> weakReference;
    //private static LoadingUtils mInstance;
    private boolean cancelable;
    private Dialog mDialog;
    private WeakReference<View> imgLoading;

    private MyHandler mHandler;
    private float mRotateDegrees;
    private int mFrameTime;

    public LoadingUtils(Context context) {
        weakReference = new WeakReference<>(context);
        mHandler = new MyHandler(this);
    }

    public static  LoadingUtils create(Context context) {
        return new  LoadingUtils(context);
    }

    /**
     * 是否可取消
     * @param cancelable
     * @return
     */
    public  LoadingUtils setCancellable(boolean cancelable) {
        this.cancelable = cancelable;
        return this;
    }

    /**
     * 显示
     */
    public  LoadingUtils show() {
        LayoutInflater inflater = LayoutInflater.from(weakReference.get());
        View view = inflater.inflate(R.layout.dialog_loading, null);
        imgLoading = new WeakReference<>(view.findViewById(R.id.img_loading));
        mFrameTime = 1000 / 12;

        mDialog = new Dialog(weakReference.get(), R.style.LoadingDialog);
        mDialog.setContentView(view);
        mDialog.setCancelable(cancelable);
        mDialog.setCanceledOnTouchOutside(false);

        mDialog.show();

        mHandler.post(new MyRunnable(this));

        setCancellable(true);

        return this;
    }

    /**
     * 隐藏
     */
    public void dismiss() {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
    }

    private static class MyHandler extends Handler {
        private WeakReference<LoadingUtils>reference;
        private MyHandler( LoadingUtils mLoading){
            reference = new WeakReference<>(mLoading);
        }
    }

    private static class MyRunnable implements Runnable{
        WeakReference<LoadingUtils> reference;
        private MyRunnable( LoadingUtils mLoading){
            reference = new WeakReference<>(mLoading);
        }

        @Override
        public void run() {
             LoadingUtils mLoading = reference.get();
            if (mLoading == null)   return;

            mLoading.mRotateDegrees += 30;
            mLoading.mRotateDegrees = mLoading.mRotateDegrees < 360 ? mLoading.mRotateDegrees : mLoading.mRotateDegrees - 360;
            mLoading.imgLoading.get().setRotation(mLoading.mRotateDegrees);
            mLoading.mHandler.postDelayed(this, mLoading.mFrameTime);
        }
    }
}
